import processing.opengl.*;
import processing.pdf.*;
import toxi.geom.*;
import unwrap.*;


// unwrap
Unwrap u;
ArrayList t;

// cameravector
Vec3D cam = new Vec3D(0,0,0);

//PDF
PGraphicsPDF pdf;


void setup() {
  size(1024,768, OPENGL);
  // initialise PDF
  pdf = (PGraphicsPDF) createGraphics(width, height, PDF, "unwrapping.pdf");
  // do first draw
  update();
}

void update() {
  // initialise Unwrap
  u = new Unwrap(this,createFont("rock.ttf",48));

  //////////////////// calculate Cylinder
  float degree, num, cosval, sinval, xr, yr;
  xr = 200;
  yr = 200;
  num = random(4,20);
  degree = radians(360 / num);

  //begin triangleStrip
  u.beginStrip();
  for (int i = 0; i < num ; i++) {
    cosval = cos(degree * i);
    sinval = sin(degree * i);

    // add Points to Strip
    u.addPoint(cosval * xr, -yr, sinval * xr*random(2));
    u.addPoint(cosval * xr, yr, sinval * xr*random(2));
  }
  // end and close Strip 
  u.endStrip(CLOSE);
}


void draw() {
  background(200);
  stroke(255);
  fill(200);
  lights();

  // camera
  float d=frameCount;
  cam.x=sin(radians(d))*mouseX*4;
  cam.y=mouseY*4-height;
  cam.z=cos(radians(d))*mouseX*4;
  camera(cam.x,cam.y,cam.z,0,0,0,0,1,0);

  //////////////////// draw 3d
  u.draw3d();
  u.drawNormals();

  //////////////////// draw 2d
  camera();
  noFill();

  // get 2d Triangles
  t = u.triangles;
  //... and draw them twodimensional
  for(Iterator i=t.iterator(); i.hasNext();) {
    UTriangle tri=(UTriangle)i.next();
    tri.draw2d(new Vec2D(width/2, height/2));
    // draw info Text for assembling
    tri.drawNeighborInfoText(10);
  }

}

//////////////////// save PDF
void keyReleased(){  
  // get 2d Triangles
  t = u.triangles;
  // record PDF
  PGraphicsPDF pd = (PGraphicsPDF) pdf;
  pdf.beginDraw();
  pdf.stroke(0);
  int idx=0;
  for(Iterator i=t.iterator(); i.hasNext();) {
    UTriangle tri=(UTriangle)i.next();
    pdf.noFill();
    //... and draw them twodimensional
    tri.draw2d(new Vec2D(width/2, height/2),pdf);
    pdf.fill(0);
    // draw info Text for assembling
    tri.drawNeighborInfoText(10,pdf);
    // add new Page
    pd.nextPage();
    println(idx++);
  }
  pdf.dispose();
  pdf.endDraw();
  println("pdf_saved");
}


void mouseReleased() {
  update();
}

